package com.quectel.cms.controller.help;


import com.quectel.business.common.help.FeedbackBusiness;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.help.FeedBackConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.help.dto.FeedbackDto;
import com.quectel.core.module.help.service.FeedbackService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/04/24 18:38
 */
@RestController
@RequestMapping("feedback")
@Tag(name = "FeedbackController", description = "意见反馈相关api")
public class FeedbackController extends BaseController {

    @DubboReference
    private FeedbackService feedbackService;
    @Autowired
    private FeedbackBusiness feedbackBusiness;

    /**
     * 列表
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "feedback:exportExcel")
    @Operation(summary = "导出记录")
    public void exportExcel(HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));
        Map<String, Object> params = request.getParams();
        super.fillAuthorityData(params);

        List<FeedbackDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<FeedbackDto> list = feedbackService.queryList(params);
            for (FeedbackDto dto : list) {
                dto.setPersonName(feedbackBusiness.getPersonName(dto));
            }
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "人员来源", "反馈人姓名", "联系方式", "意见内容", "状态", "创建时间"};
        List<String[]> dataList = new ArrayList<>();
        for (FeedbackDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageName();
            item[1] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.FEEDBACK_PERSON_TYPE, String.valueOf(data.getPersonType()));
            item[2] = data.getPersonName();
            item[3] = data.getMobile();
            item[4] = data.getContent();
            item[5] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.FEEDBACK_STAUTS, String.valueOf(data.getStatus()));
            item[6] = data.getCreateTime() == null ? "" : DateUtils.format(data.getCreateTime(), DateUtils.FormatType.COMMON);
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "意见反馈", headers, dataList, "意见反馈");

    }

    /**
     * 批量处理
     *
     * @param ids
     * @return
     */
    @PostMapping("deal")
    @RequirePermissions(values = "feedback:deal")
    @Operation(summary = "批量处理意见反馈")
    public Response<Object> deal(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (feedbackService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        for (Long id : ids) {
            FeedbackDto updately = new FeedbackDto();
            updately.setId(id);
            updately.setStatus(FeedBackConstants.DealStatus.COMPLETE.getStatus());
            feedbackService.updateById(updately);
        }

        return Response.ok();
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "feedback:list")
    @Operation(summary = "分页获取意见反馈列表")
    public Response<Page<FeedbackDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        if (StringUtils.isNotBlank(request.getString(FeedBackConstants.PERSON_NAME))){
            List<Long> ids = feedbackBusiness.getIdList(request.getString(FeedBackConstants.PERSON_NAME));
            if (CollectionUtils.isNotEmpty(ids)){
                logger.debug("通过名称查询到的用户ids:{}", ids);
                request.put(FeedBackConstants.PERSONIDS, ids);
                request.getParams().remove(FeedBackConstants.PERSON_NAME);
            }
        }

        int total = feedbackService.queryTotal(request.getParams());

        List<FeedbackDto> list = null;
        if (total > 0) {
            list = feedbackService.queryList(request.getParams());
            for (FeedbackDto dto : list) {
                dto.setPersonName(feedbackBusiness.getPersonName(dto));
            }
        } else {
            list = new ArrayList<>();
        }

        Page<FeedbackDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<FeedbackDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "feedback:edit")
    @Operation(summary = "在编辑时根据id查询意见反馈详情")
    public Response<FeedbackDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (feedbackService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        FeedbackDto feedbackDto = feedbackService.selectById(id);

        return Response.<FeedbackDto>ok().wrap(feedbackDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "feedback:info")
    @Operation(summary = "根据id查询意见反馈的详情")
    public Response<FeedbackDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (feedbackService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        FeedbackDto feedbackDto = feedbackService.selectById(id);
        feedbackDto.setPersonName(feedbackBusiness.getPersonName(feedbackDto));

        return Response.<FeedbackDto>ok().wrap(feedbackDto);
    }

    /**
     * 保存
     *
     * @param feedbackDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "feedback:edit")
    @Operation(summary = "新增意见反馈")
    public Response<Object> save(@RequestBody @Validated FeedbackDto feedbackDto) {

        //填充基础数据
        fillSaveCommonData(feedbackDto);

        feedbackService.save(feedbackDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param feedbackDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "feedback:edit")
    @Operation(summary = "根据id修改意见反馈")
    public Response<Object> update(@RequestBody @Validated FeedbackDto feedbackDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(feedbackDto.getId()));
        if (feedbackService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(feedbackDto);

        feedbackService.updateById(feedbackDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "feedback:delete")
    @Operation(summary = "根据多条记录id批量删除意见反馈")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (feedbackService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        feedbackService.deleteBatch(ids);

        return Response.ok();
    }
}
